import _ from 'lodash';
import axios from 'axios';

import router from '@/router'
import NProgress from "nprogress";
import { ElMessage,ElMessageBox } from 'element-plus'
function util(_context) {
  "use strict";
  if (!arguments)
    throw new Error('缺少Vue上下文 this ');
  let $this = _context;
//  axios.defaults.baseURL = 'http://127.0.0.1:8081'  //BASE_API
  axios.defaults.baseURL = process.env.VUE_APP_API_BASE_URL
  //axios.defaults.baseURL = '/'
 /* axios.defaults.headers.common['Authorization'] =  30 * 1000;*/
  axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';



  const pretreatment = (action, payload, handler, call) => {
    if (handler && _.isFunction(handler)) {
      payload = handler.call(this, payload);
    }
    let controller = '';
    let method = '';
    if (_.isString(action)) {
      controller = action.split('.')[0];
      method = action.split('.')[1];
    } else {
      controller = action.controller;
      method = action.method;
    }
    return call(controller, method, payload)
  }
  // 添加响应拦截器
  axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    return Promise.reject(error);
  });


  // 直接 ajax 访问后台异步
  this.ajax = (action, payload, handler) => {
    return pretreatment(action, payload, handler, (controller, method) => {
      return new Promise((resolve, reject) => {
        let header = {}
        if( window.localStorage.getItem("token")){
          header = {
            'Authorization': window.localStorage.getItem("token") ,

          }
        }
        let obj = require(`../actions/api/${controller}.js`).default.actions[method]
        let data;
        let params;
        if("post" === obj.method){
          data = payload
        }else{
          params = payload
        }
        NProgress.start();
        axios({
          method: obj.method,
          headers:header,
          url: obj.url(),
          data: data,
          params:params
        }).then(response => {
          NProgress.done();
          // 请求成功
          resolve(response.data)
        }).catch(err => {
          NProgress.done();
          if(err.response.data.code == 403){
            router.push( "/")
          }
          ElMessage.$message.error(err.response.data.message);
          reject(err)
        })
      })
    })
  }


  /**
   * post方法，对应post请求
   * @param {String} url [请求的url地址]
   * @param {Object} params [请求时携带的参数]
   */
  this.post = (url, params) =>{
    let header = {}
    if( window.localStorage.getItem("token")){
      header = {
        'Authorization': window.localStorage.getItem("token") ,

      }
    }
    return new Promise((resolve, reject) => {
      axios.post(url,
          params,{
            headers: header
          })
          .then(res => {
            resolve(res.data);
          })
          .catch(err => {
            reject(err.data)
          })
    });
  }

/*  this.getDict = async  (classifyCode)=>{
    let map = new Map();
    return   this.ajax(NmDictController.queryDictListByClassifyCode,{classifyCode:classifyCode}).then(res=>{

       res.filter(res=>{
         map.set(res.dictCode,res.dictName)
       })
      return map;
     })

  }*/


  this.hint = (value)=>{
    const hintMessage = JSON.parse(value)
    ElMessage.success(hintMessage.message)

  }
  this.del = async (title,action,param,reload)=>{
    ElMessageBox.confirm(title + ', 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      this.ajax(action,param).then(res=>{
        this.hint(res.message)
        reload()
      })

    }).catch(() => {
      ElMessage.info("已取消删除")
    });
  }
  this.formVerify = (formName,med,loading)=> {
    $this.$refs[formName].validate((valid) => {
      if (valid) {
        med()
      } else {
        $this[loading] = false
        $this.$message.warning("请完善表单");
        return false;
      }
    });
  }
  this.formVerifyV3 = (ref,med,errMed)=> {
    ref.validate((valid) => {
      if (valid) {
        med()
      } else {
        errMed()
        ElMessage.warning("请完善表单");
        return false;
      }
    });
  }

  this.getResponse = (value) =>{
    return JSON.parse(value.message)
  }
}

export default (context, defaultEntity) => new util(context, defaultEntity);
